package com.chinaoct.siku.LocalStorage.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.chinaoct.siku.LocalStorage.config.FileProperties;
import com.chinaoct.siku.LocalStorage.dao.StorageDTO;
import com.chinaoct.siku.LocalStorage.dao.StorageVO;
import com.chinaoct.siku.LocalStorage.entity.Storage;
import com.chinaoct.siku.LocalStorage.repository.StorageRep;
import com.chinaoct.siku.LocalStorage.util.FileUtil;
import com.chinaoct.siku.LocalStorage.util.PicUtils;
import com.chinaoct.siku.util.DateUtils;
import com.chinaoct.siku.util.exception.CheckException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    private FileProperties properties;

    @Autowired
    private StorageRep storageRep;


    @Value("${file.host}")
    private String imgHost;
    @Value("${file.requestPath}")
    private String requestPath;

    @Value("${file.requestPathToken}")
    private String requestPathToken;


    @Override
    public StorageDTO create(String key, File file,String fileName,Integer storageType,String source) {
        StorageDTO old = this.findByRealName(key);
        if(null!=old){
            return old;
        }
        FileUtil.checkSize(properties.getMaxSize(), file.length());
        String suffix = FileUtil.getExtensionName(file.getName());
        String type = FileUtil.getFileType(suffix);
        String month= DateUtils.format(new Date(),"yyyyMM");

        if(ObjectUtil.isNull(file)){
            throw new RuntimeException("上传失败");
        }
        try {
            String realName=file.getName();
            if(StringUtils.isBlank(key)){
                if(realName.indexOf(".")>0){
                    key=realName.substring(0,realName.lastIndexOf("."));
                }else {
                    key = realName;
                }
            }
            if(StringUtils.isBlank(fileName)){
                fileName = realName;
            }
            Storage localStorage = new Storage(
                    key,
                    fileName,
                    suffix,
                    file.getPath(),
                    type,
                    FileUtil.getSize(file.length()),
                    storageType
            );
            localStorage.setSource(source);
            if(type==FileUtil.IMAGE){
                try {
                    String destPath=properties.getPath().getPath() + month +  File.separator +"thumbnail" +File.separator;
                    String  thumbnailPath=destPath+ UUID.randomUUID().toString() +"."+suffix;
                    File dest = new File(destPath).getCanonicalFile();
                    // 检测是否存在目录
                    if (!dest.exists()) {
                        if (!dest.mkdirs()) {
                            log.error("was not successful.");
                        }
                    }
                    PicUtils.resize(file.getPath(),thumbnailPath);
                    localStorage.setThumbnail(thumbnailPath);
                }catch (Exception ex){
                    log.error("压缩图片失败",ex);
                }
            }
            storageRep.save(localStorage);
            StorageDTO dto=new StorageDTO();
            BeanUtils.copyProperties(localStorage,dto);
            StorageVO vo =new StorageVO(1,key,dto.getPath(),dto.getThumbnail());
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(vo);
            return  dto;
        }catch (Exception e){
            log.info("---------------------1234------------------------");
            old = this.findByRealName(key);
            if(null!=old){
                return old;
            }else{
                FileUtil.del(file);
                throw e;
            }
        }
    }

    @Override
    public void update(StorageDTO resources) {

    }

    @Override
    public StorageDTO findByRealName(String realName) {
        if(StringUtils.isBlank(realName)){
            throw new CheckException("-1","文件key不能为空");
        }
        Storage storage = storageRep.findByRealName(realName);
        if(null == storage){
            return null;
        }
        StorageDTO dto=new StorageDTO();
        BeanUtils.copyProperties(storage,dto);
        return  dto;
    }

    @Override
    public StorageDTO saveFile(String name,String sourceType, MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        String month= DateUtils.format(new Date(),"yyyyMM");
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + month +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new RuntimeException("上传失败");
        }
        try {
            String realName=file.getName();
            if(realName.indexOf(".")>0){
                realName=realName.substring(0,realName.lastIndexOf("."));
            }
            Storage localStorage = new Storage(
                    realName,
                    name,
                    suffix,
                    file.getPath(),
                    type,
                    FileUtil.getSize(file.length()),
                    1
            );
            localStorage.setSource(sourceType);
            if(type==FileUtil.IMAGE){
                try {
                    String destPath=properties.getPath().getPath() + month +  File.separator +"thumbnail" +File.separator;
                    String  thumbnailPath=destPath+ UUID.randomUUID().toString() +"."+suffix;
                    File dest = new File(destPath).getCanonicalFile();
                    // 检测是否存在目录
                    if (!dest.exists()) {
                        if (!dest.mkdirs()) {
                            log.error("was not successful.");
                        }
                    }
                    PicUtils.resize(file.getPath(),thumbnailPath);
                    localStorage.setThumbnail(thumbnailPath);
                }catch (Exception ex){
                    log.error("压缩图片失败",ex);
                }
            }
            storageRep.save(localStorage);
            StorageDTO dto=new StorageDTO();
            BeanUtils.copyProperties(localStorage,dto);
            return  dto;
        }catch (Exception e){
          log.error(e.getMessage(),e);
        }
        return null;
    }

    @Override
    public boolean deleteById(Long id) {
        Storage storage = storageRep.getOne(id);
        if(null != storage){
            if(StringUtils.isNotBlank(storage.getPath())){
                File file = new File(storage.getPath());
                if(file.exists()){
                    file.delete();
                }
            }
            if(StringUtils.isNotBlank(storage.getThumbnail())){
                File file = new File(storage.getThumbnail());
                if(file.exists()){
                    file.delete();
                }
            }
            storageRep.delete(storage);
            return true;
        }
        return false;
    }

    @Override
    public StorageVO changeToStorageVO(StorageDTO storage) {
        StorageVO vo =new StorageVO();
        vo.setRealName(storage.getRealName());
        String imgUrl=imgHost+requestPath+storage.getRealName();
        if(StringUtils.isNotBlank(storage.getSource())){
            if(!FileProperties.LANLIN_SOURCE.equals(storage.getSource())){
                imgUrl=imgHost+requestPathToken+storage.getRealName();
            }
        }
        vo.setPath(imgUrl);
        vo.setThumbnail(imgUrl+"?thumbnail=1");
        vo.setId(storage.getId());
        return vo;
    }


}
